package com.it.demo.realm;

import com.it.demo.entity.User;
import com.it.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;


public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 实现授权逻辑
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获得当前subject
        Subject subject = SecurityUtils.getSubject();
        //获得当前的principal,也就是认证完后我们放入的信息
        User currentUser = (User) subject.getPrincipal();
        //添加权限
        info.addStringPermissions(currentUser.getPerms());

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 实现认证逻辑
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //从数据库中查询该用户
        String username = usernamePasswordToken.getUsername();
        User user = userService.getByUsername(username);
        //如果不存在该用户，返回一个空错误，前端也可以相应显示提示
        if (user == null) {
            return null;
        }
        // 第一个参数为principal，就是授权方法里面拿到的那个对象;
        // 第二个参数为从数据库中查出的用于验证的密码，shiro中密码验证不需要我们自己去做；
        // 第三个参数为 realmName
        return new SimpleAuthenticationInfo(user,user.getPwd(),getName());
    }
}
